<template>
    <div class="box">
        <div v-show="showGoodsEditBoolean">
            <div class="table-title">{{ definePropsMsg.tableTitle }}</div>
            <div class="table-action-box">
                <div class="action-item">商品名称：<el-input v-model="goodName" placeholder="请输入商品名称"></el-input></div>
                <div class="action-item">商品编码：<el-input v-model="goodID" disabled placeholder="请输入商品编码"></el-input>
                </div>
                <div class="action-item">商品分类：
                    <el-tree-select v-model="goodType" :data="goodsTypeList" check-strictly placement="bottom"
                        :props="goodsTypeListTreeProps" :render-after-expand="false" placeholder="请选择商品分类" />
                </div>
                <el-button type="primary" class="table-actionBox-addBtn"
                    @click="currentPage = 1; loadGoodsList(currentPage, tablePagination.pageSize, goodType, goodName, goodID)">
                    <el-icon>
                        <Search />
                    </el-icon><span>搜索</span>
                </el-button>
            </div>
            <div class="action-item">
                <el-button class="action-item-btn" @click="chooseType(0)" id="typeBtn">全部</el-button>
                <el-button class="action-item-btn" @click="chooseType(1)" id="typeBtn">出售中</el-button>
                <el-button class="action-item-btn" @click="chooseType(2)" id="typeBtn">已下架</el-button>
                <el-button class="action-item-btn" @click="chooseType(3)" id="typeBtn">已售罄</el-button>
                <el-button type="primary" class="table-actionBox-addBtn" @click="goodOperate(1)">
                    <span class="table-actionBox-addBtn-icon">+</span><span>创建商品</span>
                </el-button>
            </div>

            <table class="table" v-loading="tableDataLoading">
                <tr>
                    <th><input type="checkbox" name="chooseAll" id=""></th>
                    <th>商品ID</th>
                    <th>商品图片</th>
                    <th>商品名称</th>
                    <th>商品价格</th>
                    <th>总销量</th>
                    <th>库存总量</th>
                    <th>状态</th>
                    <th>排序</th>
                    <th>更新时间</th>
                    <th>操作</th>
                </tr>
                <tr v-if="tableData.length > 0" v-for="i of tableData">
                    <td><input type="checkbox" name="chooseAll" id=""></td>
                    <td>{{ i.good_id }}</td>
                    <td class="good-img-box">
                        <img v-if="imgSrcFormat(i.img)" :src="i.img" alt="" class="good-img">
                        <span v-else style="color: orange;">bad src</span>
                    </td>
                    <td>{{ i.good_name }}</td>
                    <td>{{ i.price }}</td>
                    <td>0</td>
                    <td>999</td>
                    <td>上架</td>
                    <td>100</td>
                    <td>{{ Format.timeFormat(i.update_time) }}</td>
                    <td class="edit-btn">
                        <span @click="goodOperate(2, i)">编辑</span>
                        <span @click="goodOperate(0, i)">删除</span>
                    </td>
                </tr>
                <tr v-else>
                    <td colspan="11" style="border-bottom: none;">
                        <el-empty description="No Data" />
                    </td>
                </tr>
            </table>
            <el-pagination v-if="tableData.length > 0" class="table-pagination" :page-size="tablePagination.pageSize"
                layout="prev, pager, next" :total="tablePagination.total" v-model:current-page="currentPage" />
        </div>

        <GoodsEdit v-show="!showGoodsEditBoolean" :goodInfoDetail="goodInfoDetail" :goodsTypeList="goodsTypeList"
            @showBoolean="showBoolean">
        </GoodsEdit>
    </div>
</template>
<script setup>
import { ref, getCurrentInstance, watch, onMounted, reactive } from 'vue';
import { Format } from '/util/CommonFunctions.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import GoodsEdit from './goodsEdit/goodEdit.vue'
const token = window.localStorage.getItem('token')
const { proxy } = getCurrentInstance()

let definePropsMsg = defineProps(['tableTitle']) //从父组件接收到的表格标题

const goodsTypeListTreeProps = { children: 'children', label: 'type_name' } // 树形选择匹配值
let goodsTypeList = ref([]) // 商品分类数组

let goodInfoDetail = ref() // 商品信息

let goodType = ref() // 树形选择的值 商品二级分类 对应参数good_type
let goodName = ref() // 商品名称 对应参数search
let goodID = ref() // todo

let tableData = ref([]) // 商品列表数据
let tablePagination = ref({ pageSize: 9, total: 0 }) // 分页
let currentPage = ref(1) // 分页激活项 默认第一页
let tableDataLoading = ref(false) // 加载动画

let showGoodsEditBoolean = ref(true) // 显示编辑组件与否
const showBoolean = (e) => { showGoodsEditBoolean.value = e } // 子组件传来的值 关闭编辑组件

loadGoodsTypeList() // 商品分类列表
loadGoodsList(1) // 商品列表 page, size, (good_type, search, is_new) ()为非必选

watch(() => goodType.value, (newOne, oldOne) => { // 商品分类切换 切换分类时 还原到第一页 条目数归零
    currentPage.value = 1
    tablePagination.value.total = 0
})

watch(() => currentPage.value, (newVal, oleVal) => { //监听页码改变
    loadGoodsList(newVal, tablePagination.value.pageSize, goodType.value, goodName.value, goodID.value);
})

onMounted(() => { // 商品分类切换 按钮 不是下拉列表
    const typeBtn = document.querySelectorAll('#typeBtn')
    chooseType(0) // 商品分类切换按钮 默认激活第一项
})

function loadGoodsTypeList() { // 商品分类列表 
    const promiseRes = proxy.$reqFuncAxios('post', 'api/admin/goodsTypeList', { token: token })
    promiseRes.then(res => {
        if (res.data.code === 2000) { // 请求成功
            let temp = [];
            getChildren(temp, 0, res.data.data);
            let chooseAllGoods = { "value": 'good_type_choose_all', "type_name": "全部分类", "parent_id": 0, }
            temp.unshift(chooseAllGoods)
            goodsTypeList.value = temp //需要传值给子组件
        }
    })
}

function loadGoodsList(page, size, good_type, search, is_new) { // 商品列表
    tableDataLoading.value = true
    let query = { token: token, page: page ? page + '' : 1 + '', size: size ? size + '' : tablePagination.value.pageSize + '' }
    if (good_type === 'good_type_choose_all') { good_type = undefined }
    if (good_type) { query.good_type = good_type + '' }
    if (search) { query.search = search + '' };
    // if (is_new) { query.is_new = is_new + '' }
    // console.log(query);
    const promiseRes = proxy.$reqFuncAxios('post', 'api/admin/goodList', query)
    promiseRes.then(e => {
        tableData.value = e.data?.data?.data
        tablePagination.value.total = e.data.data.count
        tableDataLoading.value = false
    })
}

function chooseType(e) { // 商品分类切换按钮
    for (let item of typeBtn) { item.classList.remove('action-item-btn-active') }
    typeBtn[e].classList.toggle('action-item-btn-active')
}

function goodOperate(type, i) { //商品操作  0删除 1新增 2编辑
    if (type === 0) { console.log('删除'); }
    else if (type === 1) { console.log('新增'); showGoodsEditBoolean.value = false; }
    else {
        showGoodsEditBoolean.value = false
        const promiseRes = proxy.$reqFuncAxios('post', 'api/admin/goodInfo', { token: token, good_id: i.good_id })
        promiseRes.then(res => { goodInfoDetail.value = res.data.data; })//传值给子组件 // 获取商品信息成功时
    }
}

function imgSrcFormat(src) { // 图片地址校验 消除报错 // 会执行两次 // onLoad onError
    return src.match('http://api_devs.wanxikeji.cn/') || src.match('https:')
}

function getChildren(resTree, pid, originData) { // 扁平化数据 转 树结构 // 结果数组 parent_id 扁平化数据 //https://juejin.cn/post/6987224048564437029#comment
    for (let i of originData) {
        if (i.parent_id === pid) {
            const newOne = { value: i.good_type_id, children: [], ...i }
            resTree.push(newOne)
            getChildren(newOne.children, newOne.good_type_id, originData)
        }
    }
}

function findChildren(node = [], pid, arr = []) { // 遍历树形结构
    // let findChildrenRes = findChildren(goodsTypeList.value, goodInfoDetail.type_id)
    for (let item of node) {
        arr.push(item)
        if (item.value == pid) { return item }
        else if (item.children && item.children.length) { return findChildren(item.children, pid, arr) }
    }
}

</script>
<style scoped>
.box {
    margin: 16px 20px;
    padding: 24px;
    background-color: #fff !important;
    display: block !important;
    min-width: fit-content;
    max-width: 100%;
}

.table input[type=checkbox] {
    cursor: pointer;
}

.table td {
    max-width: 180px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.table-title {
    font-size: 16px;
    color: rgba(0, 0, 0, .75);
    margin-bottom: 16px;
}

.table-action-box {
    margin-bottom: 18px;
    display: flex;
    line-height: 1.5;
    color: rgba(0, 0, 0, .65);
    transition: all .3s;
}

.table-actionBox-addBtn {
    border-radius: 2px;
    transition: all .3s;
    height: 32px;
}

.table-actionBox-addBtn:deep() .el-button:hover {
    border-color: #40a9ff;
    color: inherit;
}

.table-actionBox-addBtn-icon {
    margin-right: 5px;
    font-size: 20px;
}

.action-item {
    white-space: nowrap;
    display: flex;
    align-items: center;
    margin-right: 10px;
    color: rgba(0, 0, 0, .85);
    font-size: 14px;
    width: 290px;
}

.action-item :deep() .el-input__wrapper:hover {
    box-shadow: 0 0 0 1px #40a9ff inset;
}

.action-item :deep() .el-button:hover {
    border-color: #40a9ff;
}

.action-item :deep() .el-tooltip__trigger {
    justify-content: space-between;
    width: 220px;
}

.action-item :deep() .el-tooltip__trigger>span {
    width: 100%;
    justify-content: space-between;
}

.action-item-btn {
    margin: 0;
    border-radius: 0;
    height: 32px;
    transition: all .3s;
}

.action-item-btn-active {
    border-color: #40a9ff;
    background-color: #ECF5FF;
    color: #40a9ff;
}

.table {
    margin-top: 18px;
}

.table .good-img-box {
    width: 30px;
    height: 30px;
}

.table .good-img {
    max-width: 100%;
    max-height: 100%;
}

.edit-btn {
    color: #1890ff;
    text-decoration: none;
    background-color: transparent;
    outline: none;
}

.edit-btn span {
    cursor: pointer;
    transition: color .3s;
    margin-right: 5px;
}

.edit-btn span:hover {
    color: #40a9ff;
}

.table-pagination {
    margin: 0 auto;
    width: fit-content;
    margin-top: 20px;
}
</style>